package com.sorted.ad;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.applovin.mediation.MaxAd;
import com.applovin.mediation.MaxError;
import com.applovin.mediation.MaxReward;
import com.applovin.mediation.MaxRewardedAdListener;
import com.applovin.mediation.ads.MaxRewardedAd;
import com.sorted.SortConstant;
import com.sorted.utils.SortADManager;


public class SortMaxReward {
    private static SortMaxReward adManager;
    private MaxRewardedAd maxRewardedAd;
    private String adSource="";

    public static SortMaxReward getInstance() {
        if (adManager == null) {
            adManager = new SortMaxReward();
        }
        return adManager;
    }

    private MaxRewardedAd getRewardedAd(Context context,String adUnitId) {
        return MaxRewardedAd.getInstance(adUnitId);
    }

    public void loadRewardAd(Context context) {
        maxRewardedAd =getRewardedAd(context, SortConstant.REWARD_PLACEMENTID);
        setListner();
        loadRewardAd();
    }

    private void loadRewardAd(){
        maxRewardedAd.loadAd();
    }


    private void setListner() {
        maxRewardedAd.setListener(new AdListener());
    }

    public boolean isReady(){
        if (maxRewardedAd != null) {
            return maxRewardedAd.isReady();
        }
        return false;
    }

    public void showAd(Activity activity, String adSource) {
        if (!TextUtils.isEmpty(adSource)){
            this.adSource = adSource;
        }
        getRewardAD(activity);
        setListner();
        show(activity);
    }

    private void show(Activity activity) {
        if (isReady()) {
            maxRewardedAd.showAd(activity);
        } else {
            SortADManager.getInstance().callbackAdError();
            loadRewardAd();
        }
    }

    private void getRewardAD(Activity activity) {
        if (maxRewardedAd == null) {
            maxRewardedAd =getRewardedAd(activity, SortConstant.REWARD_PLACEMENTID);
        }
    }

    public class AdListener implements MaxRewardedAdListener{

        @Override
        public void onUserRewarded(@NonNull MaxAd maxAd, @NonNull MaxReward maxReward) {

        }

        @Override
        public void onAdLoaded(@NonNull MaxAd maxAd) {

        }

        @Override
        public void onAdDisplayed(@NonNull MaxAd maxAd) {
        }

        @Override
        public void onAdHidden(@NonNull MaxAd maxAd) {
            loadRewardAd();
            SortADManager.getInstance().callbackAdOver(adSource);
        }

        @Override
        public void onAdClicked(@NonNull MaxAd maxAd) {

        }

        @Override
        public void onAdLoadFailed(@NonNull String s, @NonNull MaxError error) {
        }

        @Override
        public void onAdDisplayFailed(@NonNull MaxAd maxAd, @NonNull MaxError error) {
            SortADManager.getInstance().callbackAdError();
        }
    }


}
